package cn.estore.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
	// 数据库驱动类名，方便后续统一修改
	private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
	// 数据库连接URL，方便后续统一修改
	private static final String DB_URL = "jdbc:mysql://localhost:3306/estoredb?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true";
	// 数据库用户名，方便后续统一修改
	private static final String DB_USERNAME = "root";
	// 数据库密码，方便后续统一修改
	private static final String DB_PASSWORD = "123";

	private Connection conn;

	public DBConnection() {
		try {
			// 加载数据库驱动
			Class.forName(DB_DRIVER);
			// 获取数据库连接
			establishConnection();
		} catch (ClassNotFoundException e) {
			System.err.println("找不到数据库驱动类，请检查相关依赖是否引入正确。");
			e.printStackTrace();
		} catch (SQLException e) {
			System.err.println("数据库连接建立出现异常，请检查数据库配置等是否正确。");
			e.printStackTrace();
		}
	}

	private void establishConnection() throws SQLException {
		conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
	}

	public Connection getConnection() {
		return conn;
	}

	public void closeConnection() {
		if (conn!= null) {
			try {
				conn.close();
			} catch (SQLException e) {
				System.err.println("关闭数据库连接出现异常。");
				e.printStackTrace();
			}
		}
	}
}
